<template>
  <div class="van-cell van-cell-clear">
    <van-cell :title="label" :required="required">
      <file-upload
        v-if="!readonly"
        class="mb-uploader"
        :ref="item.name"
        name="fdata"
        :input-id="item.name"
        v-model="comfiles"
        :size="size"
        :accept="accept"
        :multiple="multiple"
        :post-action="postAction"
        @input-file="inputFile"
        @input-filter="inputFilter"
      >
        <van-icon name="add-o" size="20px" style="line-height: inherit;"/>
      </file-upload>
    </van-cell>
    <div class="van-field__error-message" v-if="errorMessage" style="padding-left: 106px;">{{errorMessage}}</div>
    <van-card
      v-for="(file, index) in comfiles"
      :key="index"
      :title="file.name"
      style="background-color: #fff;"
    >
      <van-icon slot="thumb" name="description" size="36px" style="line-height: inherit;"/>
      <div slot="desc">
        <span>{{filesize(file.size)}}</span>
        <span v-if="!readonly" style="color: #1989fa;margin-left: 8px" @click="deleteHandler(file)">删除</span>
        <span v-if="!file.data" style="color: #1989fa;margin-left: 8px" @click="getPreviewFiles(file)">预览</span>
      </div>
    </van-card>
  </div>
</template>

<script>
import filesize from 'utils/filesize' 

export default {
  name: 'mb-uploader',
  components: {
    FileUpload: window.VueUploadComponent
  },
  data() {
    return {
      files: [],
      errorMessage: '',
      filenumber: 99,
      filesize: filesize
    }
  },
  props: ['item','result'],
  watch: {
    // files: function(newFile) {
    //   console.log(newFile)
    // }
  },
  computed: {
    label() {
      return this.item.caption || this.item.name
    },
    required() {
      return this.item.required
    },
    readonly() {
      return this.item.readonly
    },
    size() {
      return this.item.size*1024*1024
    },
    accept() {
      let type = "*/*";
      return  this.item.type || type
    },
    multiple() {
      return this.item.multiple || true
    },
    postAction() {
      return window.contextPath + this.item.uploadUrlPre + 'upload.do'
    },
    comfiles: {
      get: function() {
        let arr = [];
        const _this = this;
        for (var prop in this.files) {
          _this.files[prop].name = prop;
          arr.push(this.files[prop]);
        }
        return arr;
      },
      set: function(newValue) {
        const _this = this;
        newValue.map(function(item) {
          item.visibility = false;
          _this.$set(_this.files, item.name, item);
        })
      }
    }
  },
  methods: {
    // 删除
    deleteHandler(file) {
      if (this.files[file.name] !== undefined) {
        this.$delete(this.files, file.name);
        this.emitChangeData();
      }
    },
    // 预览
    getPreviewFiles(file) {
      let param = "?fileName=" + file.name + "&itemName=" + this.item.name;
      if(this.item.key && Object.prototype.toString.call(this.item.key) === '[object Object]') {
        param += ("&key=" + JSON.stringify(this.item.key)) 
      }
      let url = encodeURIComponent(window.contextPath + this.item.uploadUrlPre + 'previewFile.do' + param);
      if(/\.png$|\.jpg$|\.jpeg$|\.gif$/.test(file.name)) {
        // 预览图片
        window.vant.ImagePreview({
          showIndex: false,
          images: [url],
          closeOnPopstate: true,
          onClose() {
            this.images = []
          }
        })
      } else {
        // 预览文件
        window.open(url)
      }
    },
    /**
     * Has changed
     * @param  Object|undefined   newFile   只读
     * @param  Object|undefined   oldFile   只读
     * @return undefined
     */
    inputFile(newFile, oldFile) {
      if (newFile && newFile.error && oldFile && !oldFile.error) {
        switch (newFile.error) {
          case "extension":
            newFile.error = "文件类型不允许";
            break;
          case "size":
            newFile.error = "文件太大，限制为：" + filesize(this.size)
            break;
        }
        this.$delete(this.files, newFile.name);
        this.$toast(newFile.error)
      }
      if (Boolean(newFile) !== Boolean(oldFile) || oldFile.error !== newFile.error) {
        if (!this.$refs[this.item.name].active) {
          this.$refs[this.item.name].active = true
        }
      }
      if (newFile && newFile.success === true) {
        if (Object.keys(this.files).length < this.filenumber) {
          if(newFile.response){
            let response = JSON.parse(newFile.response);
            if(response && response.code ==="1"){
              this.$delete(this.files, newFile.name);
              this.$toast(response.msg);
              return
            }
            this.$set(this.files, response.datas.name, response.datas);
            this.emitChangeData();
            this.errorMessage = '';
          }
        } else {
          this.errorMessage = '上传文件数量超过最大限制' + this.filenumber + '个~';
        }
      }
    },
    /**
     * Pretreatment
     * @param  Object|undefined   newFile   读写
     * @param  Object|undefined   oldFile   只读
     * @param  Function           prevent   阻止回调
     * @return undefined
     */
    inputFilter(newFile, oldFile, prevent) {
      if (newFile && !oldFile) {
        if (/(\/|^)(Thumbs\.db|desktop\.ini|\..+)$/.test(newFile.name)) {
          return prevent()
        }
        if (/\.(php5?|html?|jsx?)$/i.test(newFile.name)) {
          return prevent()
        }
        newFile.blob = ''
        let URL = window.URL || window.webkitURL
        if (URL && URL.createObjectURL) {
          newFile.blob = URL.createObjectURL(newFile.file);
        }
      }
    },
    validate() {
      if(this.item.required && !this.comfiles.length) {
        this.errorMessage = "* 不能为空"
        return false
      }
      return true
    },
    emitChangeData() {
      let values = {};
      for (var key in this.files) {
        values[key] = this.files[key]
      }
      let emitObj = {};
      emitObj[this.item.name] = values;
      this.$emit("formChange", this.item.name, emitObj, this.item)
    }
  },
  mounted() {
    if (this.result !== null && this.result !== "") {
      if (this.result.constructor == Object) {
        this.files = this.result;
      } else {
        this.files = JSON.parse(this.result);
      }
    }
    let emitObj = {};
    emitObj[this.item.name] = this.result;
    this.$emit("formChange", this.item.name, emitObj, this.item)
  }
}
</script>
<style scoped>
.mb-uploader.file-uploads {
  position: absolute;
  right: 0;
  top: 0;
  height: 24px;
  width: 100%;
  text-align: right;
}
.van-cell-clear {
  padding: 0;
  display: block;
}
.van-card__thumb {
  height: 36px;
  width: 36px;
  line-height: 36px;
}
.van-card__content {
  min-height: 36px;
}
</style>